package org.zjt.algorithm;

import java.util.concurrent.locks.StampedLock;

/**
 * 1、StampedLock: 读写锁
 * 2、Semaphore： 信号量
 * 3、cpu 很高：
 *      1、jps
 *      2、top -HP pid
 *      3、jstack | grep "线程id的十六进制"
 */
public class LockTest {

    private static final StampedLock stampedLock = new StampedLock();

    public static void main(String[] args) {
        //StampedLock
        for (int i = 0 ;i < 10;i ++){
            new Thread(() -> readLock()).start();
            new Thread(() -> writeLock()).start();
        }
    }

    public static void readLock() {
        long stamp = stampedLock.tryOptimisticRead(); // 获得一个乐观读锁
        if (!stampedLock.validate(stamp)) { // 检查乐观读锁后是否有其他写锁发生
            stamp = stampedLock.readLock(); // 获取一个悲观读锁
            try {
                System.out.println("---------悲观锁成功---------");
            } finally {
                stampedLock.unlockRead(stamp); // 释放悲观读锁
            }
        }else{
            System.out.println("------乐观锁成功-------");
        }
    }


    public static void writeLock() {
        long stamp = stampedLock.writeLock(); // 获取一个悲观读锁
        try {
            System.out.println("---------悲观锁成功---------");
        } finally {
            stampedLock.unlockWrite(stamp); // 释放悲观读锁
        }
    }
}
